#include "adminaddemployeeview.h"
#include "ui_adminaddemployeeview.h"
#include <QMessageBox>
#include <QRegExpValidator>
#include "adminmanager.h"
#include "sqloperator.h"
#include <QCoreApplication>

AdminAddEmployeeView::AdminAddEmployeeView(QWidget *parent) : QWidget(parent),
    ui(new Ui::AdminAddEmployeeView),
    m_adminManager(new AdminManager(this))
{
    ui->setupUi(this);

    // 设置员工ID为4位数字
    QRegExp regExp("^\\d{4}$");
    ui->empIdLineEdit->setValidator(new QRegExpValidator(regExp, this));

    // 加载部门数据
    loadDepartments();

    // 连接信号槽
    connect(ui->addButton, &QPushButton::clicked, this, &AdminAddEmployeeView::onAddButtonClicked);
    connect(ui->resetButton, &QPushButton::clicked, this, &AdminAddEmployeeView::onResetButtonClicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &AdminAddEmployeeView::onCancelButtonClicked);
    connect(m_adminManager, &AdminManager::operationResult, this, &AdminAddEmployeeView::handleOperationResult);
}

AdminAddEmployeeView::~AdminAddEmployeeView()
{
    delete m_adminManager;
    delete ui;
}

void AdminAddEmployeeView::loadDepartments()
{
    // 清空下拉框
    ui->deptIdComboBox->clear();

    // 为了简化示例，这里直接使用SqlOperator查询部门数据
    // 在实际应用中，也可以将部门查询封装到AdminManager中
    SqlOperator dbOperator;
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";
    if (dbOperator.open(dbPath, "loadDepartmentsConnection")) {
        QList<QString> fields = {"dept_id", "dept_name"};
        QList<QVariantList> data;
        if (dbOperator.selectData("department", fields, data)) {
            for (const auto &row : data) {
                int deptId = row[0].toInt();
                QString deptName = row[1].toString();
                ui->deptIdComboBox->addItem(deptName, deptId);
            }
        } else {
            QMessageBox::warning(this, "警告", "无法加载部门数据: " + dbOperator.lastError());
        }
        dbOperator.close();
    } else {
        QMessageBox::warning(this, "警告", "无法连接到数据库: " + dbOperator.lastError());
    }
}

void AdminAddEmployeeView::onAddButtonClicked()
{
    // 添加新员工
    addNewEmployee();
}

void AdminAddEmployeeView::onResetButtonClicked()
{
    ui->empIdLineEdit->clear();
    ui->empNameLineEdit->clear();
    ui->genderComboBox->setCurrentIndex(0);
    ui->positionLineEdit->clear();
    ui->deptIdComboBox->setCurrentIndex(0);
    ui->usernameLineEdit->clear();
    ui->passwordLineEdit->clear();
}

void AdminAddEmployeeView::onCancelButtonClicked()
{
    close();
}

bool AdminAddEmployeeView::validateEmployeeInfo()
{
    // 验证员工ID
    if (ui->empIdLineEdit->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "员工ID不能为空");
        return false;
    }

    // 验证员工姓名
    if (ui->empNameLineEdit->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "员工姓名不能为空");
        return false;
    }

    // 验证用户名
    if (ui->usernameLineEdit->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名不能为空");
        return false;
    }

    // 验证密码
    if (ui->passwordLineEdit->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "密码不能为空");
        return false;
    }

    // 检查员工ID是否已存在
    SqlOperator dbOperator;
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";
    if (!dbOperator.open(dbPath, "validateEmployeeConnection")) {
        QMessageBox::warning(this, "警告", "无法连接到数据库: " + dbOperator.lastError());
        return false;
    }

    QList<QString> fields = {"emp_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", ui->empIdLineEdit->text());
    QList<QVariantList> data;
    if (dbOperator.selectData("employee", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            dbOperator.close();
            QMessageBox::warning(this, "警告", "员工ID已存在");
            return false;
        }
    } else {
        dbOperator.close();
        QMessageBox::warning(this, "警告", "检查员工ID失败: " + dbOperator.lastError());
        return false;
    }

    // 检查用户名是否已存在
    whereConditions.clear();
    whereConditions.insert("username", ui->usernameLineEdit->text());
    if (dbOperator.selectData("login", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            dbOperator.close();
            QMessageBox::warning(this, "警告", "用户名已存在");
            return false;
        }
    } else {
        dbOperator.close();
        QMessageBox::warning(this, "警告", "检查用户名失败: " + dbOperator.lastError());
        return false;
    }

    dbOperator.close();
    return true;
}

bool AdminAddEmployeeView::addNewEmployee()
{
    // 验证员工信息
    if (!validateEmployeeInfo()) {
        return false;
    }

    // 调用AdminManager添加员工
    return m_adminManager->addEmployee(
        ui->empIdLineEdit->text(),
        ui->empNameLineEdit->text(),
        ui->genderComboBox->currentText(),
        ui->positionLineEdit->text(),
        ui->deptIdComboBox->currentData().toInt(),
        ui->usernameLineEdit->text(),
        ui->passwordLineEdit->text()
    );
}

void AdminAddEmployeeView::handleOperationResult(bool success, const QString &message)
{
    if (success) {
        QMessageBox::information(this, "成功", message);
        onResetButtonClicked();
    } else {
        QMessageBox::warning(this, "失败", message);
    }
}
